package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.constant.MessageConstant;
import com.atguigu.dao.MemberDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderSettingDao;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Member;
import com.atguigu.pojo.Order;
import com.atguigu.pojo.OrderSetting;
import com.atguigu.pojo.Setmeal;
import com.atguigu.service.OrderService;
import com.atguigu.service.OrderSettingService;
import com.atguigu.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author LEO
 * @Date 2021年12月22日 13:02
 */
@Service(interfaceClass= OrderService.class)  //发布服务，注册到zk中心
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
     private OrderSettingDao orderSettingDao;


    //旅游预约
    @Override
    public Result saveOrder(Map map) throws Exception {
       int setmealId = Integer.parseInt((String)(map.get("setmealId")));
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        //1.检查当前日期是否进行了预约设置(根据orderDate 查询t_ordersetting ,能查出来可以预约，查不出来不能预约)
       OrderSetting orderSetting =orderSettingDao.getOrderSettingByOrderDate(date);
        if (orderSetting==null){ // 预约设置不存在，不能预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }else {
            //2. 判断当前日期是否预约已满 ，是否等于number (最多可预约)
           int number =  orderSetting.getNumber();
            int reservations = orderSetting.getReservations();
            if (reservations>=number){
                return new Result(false,MessageConstant.ORDER_FULL);
            }
        }
        //（2）使用手机号，查询会员表，判断当前预约人是否是会员
        //获取手机号
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        //如果是会员，防止重复预约（一个会员、一个时间、一个套餐不能重复，否则是重复预约）
        if (member == null) {  // 不是会员快速注册
             member = new Member();
             member.setName((String) map.get("name"));
             member.setSex((String) map.get("sex"));
             member.setIdCard((String) map.get("idCard"));
             member.setPhoneNumber(telephone);
             member.setRegTime(new Date());
             memberDao.add(member);   //进行主键回填
        }else {//检查是否重复预约
            // 将findCountOrderByCondition()方法封装为一个通用方法，可以实现动态sql查询
            Order orderParam=new Order();
            orderParam.setOrderDate(date);
            orderParam.setSetmealId(setmealId);
            orderParam.setMemberId(member.getId());
            List<Order> orderList= orderDao.findCountOrderByCondition(orderParam);
            if (orderList != null && orderList.size()>0){
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }

        //（3）可以进行预约，更新预约设置表中预约人数的值，使其的值+1
        // 可以预约，设置预约人数加一    orderSetting前面已查到
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //（4）可以进行预约，向预约表中添加1条数据
        Order order =  new  Order();
        order.setMemberId(member.getId()); //会员id
        order.setOrderDate(date); // 预约时间
        order.setOrderStatus(Order.ORDERSTATUS_NO); // 预约状态（已出游/未出游）
        order.setOrderType((String)map.get("orderType"));
        order.setSetmealId(Integer.parseInt((String)map.get("setmealId")));
        orderDao.add(order);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order);
    }



    @Override
    public Map<String,Object> findById4Detail(Integer id) throws Exception {
        /**
         *   <p>会员姓名：{{orderInfo.member}}</p>
         *    <p>旅游套餐：{{orderInfo.setmeal}}</p>
         *    <p>旅游日期：{{orderInfo.orderDate}}</p>
         *    <p>预约类型：{{orderInfo.orderType}}</p>
         */
        Map<String, Object> map = orderDao.findById(id);
        if (map!=null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
            return map;
        }
        return map;
    }
}
